<script>
import {ref, onMounted} from 'vue';
import {ElMessage} from 'element-plus';
import {
  GetAddressInfoMessageService,
  addAddressInfoService,
  editAddressInfoService,
  DeleteAddressInfoMessageService
} from '@/api/netshop/address.js'
// import pca from '@/assets/js/pca-code.json'
import {
  regionData, CodeToText
} from 'element-china-area-data'


export default {
  name: 'Address',
  setup() {
    const addressData = ref([]);
    const addressEdit = ref([]);
    const pcaOptions = regionData;
    const addlock = ref(false)
    const loading = ref(false)
    onMounted(() => {
      loadAddressData()
    })
    const loadAddressData = async () => {
      const id = localStorage.getItem('custom_id')
      loading.value = true
      await GetAddressInfoMessageService(id)
          .then((res) => {
            console.log(res)
            addressData.value = res.data.data
            console.log(addressData.value)
          })
          .catch((err) => {
            console.log(err)
          })
          .finally(() => {
            loading.value = false
          })
      for (let i in addressData.value) {
        addressEdit.value[i] = false; //3.2 初始化布尔数组   false：查看状态（非编辑状态）
      }
    };

    const addAddress = () => {
      addlock.value = true
      addressData.value.push({}); //3.3 新增地址
      addressEdit.value[addressData.value.length - 1] = true;
    };

    const editAddress = (index) => {
      addlock.value = false
      addressEdit.value[index] = !addressEdit.value[index];
    };

    const saveAddress = async (index, value) => {
      addressEdit.value[index] = !addressEdit.value[index];
      loading.value = true
      console.log(value)
      console.log(getCodeToText(value.adpca))
      value.basic_address = getCodeToText(value.adpca)
      if (addlock.value == true) {
        if (typeof value.is_default === 'undefined') {
          value.is_default = false;
        }
        const custom_id = localStorage.getItem('custom_id')
        await addAddressInfoService(value, custom_id)
            .then((res) => {
              console.log(res)
              loading.value = false
              loadAddressData()
            })
            .catch((err) => {
              console.log(err)
            })
      } else {
        console.log(value)
        console.log(addlock)
        const custom_id = localStorage.getItem('custom_id')
        await editAddressInfoService(value, custom_id)
            .then((res) => {
              console.log(res)
              loading.value = false
              loadAddressData()
            })
            .catch((err) => {
              console.log(err)
            })
      }
    };
    const deleteAddress = async (index, value) => {
      if (value.id == undefined) {
        addressData.value.splice(index, 1)
      } else {
        console.log(value.id)
        await DeleteAddressInfoMessageService(value.id)
            .then((res) => {
              console.log(res)
              loadAddressData()
            })
            .catch((err) => {
              console.log(err)
            })
      }
    };

    const handleAddressNode = (value) => {
      // value为数组
      console.log(value)
      addressData.value.adpca = value[2]
      // 将区域码转换成汉字
      getCodeToText(value)
      console.log(CodeToText[value[0]])
      console.log(CodeToText[value[1]])
      console.log(CodeToText[value[2]])
    };
    // 将地址编码转变成字
    const getCodeToText = (codeArray) => {
      console.log(codeArray.length)
      let area = {
        'province': '',
        'city': '',
        'region': ''
      };
      switch (codeArray.length) {
        case 1:
          area += CodeToText[codeArray[0]];
          break;
        case 2:
          area += CodeToText[codeArray[0]] + "/" + CodeToText[codeArray[1]];
          break;
        case 3:
          area.province = CodeToText[codeArray[0]]
          area.city = CodeToText[codeArray[1]]
          area.region = CodeToText[codeArray[2]];
          break;
        default:
          break;
      }
      return area
    };
    const changetest = (val) => {
      console.log(typeof (val));
      console.log(val);
    };

    return {
      addressData,
      addressEdit,
      pcaOptions,
      loadAddressData,
      addAddress,
      editAddress,
      saveAddress,
      deleteAddress,
      handleAddressNode,
      changetest
    };
  }
};
</script>

<template>
  <div style="padding: 30px;">
    <el-card class="box-card" shadow="always">
      <template #header>
        <div class="card-header" style="text-align: left">
          <span>管理地址</span>
          <el-button class="button" type="text" @click="addAddress" style="float: right">新增</el-button>
        </div>
      </template>
      <el-table empty-text="当前没有地址" v-loading="loading" :data="addressData">
        <el-table-column type="index" label="序号" width="60"></el-table-column>
        <el-table-column prop="name" label="收货人" width="100">
          <template #default="scope">
            <el-input v-model="scope.row.name" v-if="addressEdit[scope.$index]"></el-input>
            <span v-else>{{ scope.row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="mobile" label="联系方式" width="140">
          <template #default="scope">
            <el-input v-model="scope.row.mobile" v-if="addressEdit[scope.$index]"></el-input>
            <span v-else>{{ scope.row.mobile }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="adpca" label="收货地址" width="240" align="center">
          <template #default="scope">
            <el-cascader
                v-model="scope.row.adpca"
                :options="pcaOptions"
                :props="addressProps"
                placeholder="请选择"
                @change="handleAddressNode"
                filterable
                :disabled="!addressEdit[scope.$index]"
            ></el-cascader>
          </template>
        </el-table-column>
        <el-table-column prop="detail" label="详细地址" width="180">
          <template #default="scope">
            <el-input v-model="scope.row.detail" v-if="addressEdit[scope.$index]"></el-input>
            <span v-else>{{ scope.row.detail }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="is_default" label="默认地址" width="100">
          <template #default="scope">
            <div v-if="addressEdit[scope.$index]">
              <el-checkbox
                  v-model="scope.row.is_default"
                  :true-label="true"
                  :false-label="false"
                  @change="changetest"
              >
                设为默认
              </el-checkbox>
            </div>
            <div v-else>
              <el-tag v-if="scope.row.is_default === true" type="success" size="mini">默认</el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="180">
          <template #default="scope">
            <el-button
                size="small"
                v-if="!addressEdit[scope.$index]"
                @click="editAddress(scope.$index)"
            >
              <el-icon>
                <Setting/>
              </el-icon>
              编辑
            </el-button>
            <el-button
                size="small"
                v-else
                @click="saveAddress(scope.$index, scope.row)"
            >保存
            </el-button>
            <el-popconfirm
                confirmButtonText="好的"
                cancelButtonText="不用了"
                icon="el-icon-info"
                title="确定删除该地址？"
                @confirm="deleteAddress(scope.$index, scope.row)"
            >
              <template #reference>
                <el-button
                    size="small"
                >
                  <el-icon>
                    <Delete/>
                  </el-icon>
                  删除
                </el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<style scoped>
.card-header {
  width: 100%;
}

</style>